package com.xiaoyy.app.extend.integration.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.xiaoyy.app.extend.common.enums.AppApiEnum;
import com.xiaoyy.app.extend.common.enums.CardTypeEnum;
import com.xiaoyy.app.extend.common.vo.*;
import com.xiaoyy.app.extend.integration.ZlbIntegration;
import com.xiaoyy.core.common.enums.EquipmentTypeEnum;
import com.xiaoyy.core.common.enums.LoginTypeEnum;
import com.xiaoyy.core.common.enums.UserTypeEnum;
import com.xiaoyy.core.common.exception.AppException;
import com.xiaoyy.core.common.vo.AppResponse;
import com.xiaoyy.core.common.vo.TokenVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ZlbIntegrationImpl implements ZlbIntegration {
    @Value("${system.config.zlb.easyAuth.url}")
    private String easyAuthUrl;
    @Value("${system.config.zlb.servicecode}")
    private String servicecode;
    @Value("${system.config.zlb.servicepwd}")
    private String servicepwd;
    @Value("${system.config.app.url}")
    private String jhApi;

    @Override
    public ZlbTicketResVO ticketValidation(ZlbTicketVO req) {
        if(StringUtils.isBlank(req.getSt())){
            throw new AppException("票据信息不能为空");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("method","ticketValidation");
        map.put("datatype","json");
        String time = DatePattern.PURE_DATETIME_FORMAT.format(new Date());
        String sign= SecureUtil.md5(servicecode+servicepwd+time);
        map.put("time",time);
        map.put("sign",sign);
        map.put("st",req.getSt());
        map.put("servicecode",servicecode);
        String body=HttpUtil.post(easyAuthUrl,map,10000);
        if(StringUtils.isBlank(body)){
            throw new AppException("浙里办未返回信息");
        }
        ZlbTicketResVO zlbTicketResVO=null;
        try{
            zlbTicketResVO= JSON.parseObject(body,ZlbTicketResVO.class);
        }catch (Exception e){
            new AppException("浙里办未返回有效json信息");
        }
        String result =zlbTicketResVO.getResult();
        //6001：st已经超时失效6002：st不是票据类型6003：st不属于该接入资源6004：st格式不对6099：其他错误
        System.out.println(result);
        if("0".equals(result)){
            return zlbTicketResVO;
        }else{
            throw new AppException(zlbTicketResVO.getErrmsg());
        }

    }

    @Override
    public ZlbUserResVO getUserInfo(ZlbTokenVO req) {
        if(StringUtils.isBlank(req.getToken())){
            throw new AppException("token信息不能为空");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("method","getUserInfo");
        map.put("datatype","json");
        String time = DatePattern.PURE_DATETIME_FORMAT.format(new Date());
        String sign= SecureUtil.md5(servicecode+servicepwd+time);
        map.put("time",time);
        map.put("sign",sign);
        map.put("token",req.getToken());
        map.put("servicecode",servicecode);
        String body=HttpUtil.post(easyAuthUrl,map,10000);
        System.out.println(body);
        if(StringUtils.isBlank(body)){
            throw new AppException("浙里办未返回信息");
        }
        ZlbUserResVO zlbUserResVO=null;
        try{
            zlbUserResVO=JSON.parseObject(body,ZlbUserResVO.class);
        }catch (Exception e){
            new AppException("浙里办未返回有效json信息");
        }
        String result =zlbUserResVO.getResult();
        //6501：令牌已经超时失效 6502: 该令牌不存在
        if("0".equals(result)){
            return zlbUserResVO;
        }else if("6501".equals(result)){
            throw new AppException(6501,zlbUserResVO.getErrmsg());
        }else if("6502".equals(result)){
            throw new AppException(6502,zlbUserResVO.getErrmsg());
        }else{
            throw new AppException(zlbUserResVO.getErrmsg());
        }
    }

    @Override
    public AppResponse<TokenVO> getToken(ZlbTokenVO req) {
        ZlbUserResVO zlbUserResVO = getUserInfo(req);
        LoginReqVO loginReqVO =new LoginReqVO();
        loginReqVO.setCardType(CardTypeEnum.idcard.getType());
        loginReqVO.setIdcard(zlbUserResVO.getIdnum());
        loginReqVO.setFullName(zlbUserResVO.getUsername());
        loginReqVO.setCellphone(zlbUserResVO.getMobile());
        loginReqVO.setUserType(UserTypeEnum.USER.getType());
        loginReqVO.setLoginType(LoginTypeEnum.zlb.getType());
        loginReqVO.setEmail(zlbUserResVO.getEmail());
        loginReqVO.setCountry(zlbUserResVO.getCountry());
        loginReqVO.setEquipmentType(EquipmentTypeEnum.APP.getType());
        loginReqVO.setOpenId(zlbUserResVO.getUserid());
        String body= HttpUtil.post(jhApi+ AppApiEnum.LOGIN0003.getType(), JSON.toJSONString(loginReqVO));
        System.out.println(body);
        return JSON.parseObject(body, AppResponse.class);
    }
}
